package com.yc.demohoudun;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.demohoudun.entiy.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.yc.demohoudun.web.UserAction.usernewName;

@Component
public class DemoInterceptor implements HandlerInterceptor {
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {

        Object loginedUser = usernewName;



        if (loginedUser == null) {

            Result result = new Result(401, "请先登录", null);

            // 设置响应编码和内容类型
            response.setContentType("application/json;charset=UTF-8");

            // 将 Result 对象转换成 JSON 格式返回给前端
            ObjectMapper objectMapper = new ObjectMapper(); // 使用 Jackson 序列化
            response.getWriter().write(objectMapper.writeValueAsString(result)); // 阻止请求继续处理
            return false;
        }

        // 如果已登录，允许继续处理请求
        return true;
    }
}
